const {sequelize} = require('../../core/db')
const {Sequelize, Model, Op} = require('sequelize');


class Comment extends Model {
    // 新增短评的接口
    static async addComment(bookId, content) {
       const comment = await Comment.findOne({
           where: {
               book_id: bookId,
               content
           }
       });
       if(!comment) {
          return await Comment.create({
            book_id: bookId,
            content,
            nums: 1
          })
       } else {  //注意此处是获取到该条数据的自增长
        return await comment.increment('nums', {
            by: 1
        })
       }
    }

    // 获取书籍短评的内容
    static async getComments(bookId) {
       const comments = await Comment.findAll({
           where: {
               book_id: bookId
           }
       });
       
       return comments;
       
    }
}

Comment.init({
    content: Sequelize.STRING(12),
    nums: {
        type: Sequelize.INTEGER,
        defaultValue: 0
    },
    book_id: Sequelize.STRING
}, {
    sequelize,
    tableName: 'comment'
});

module.exports = {
    Comment
}